//////////////////////////////////////////////////
// STUDENT RESEARCH PROJECT						//
// UNIVERSITY OF HAGEN 2012						//
// File:	Statistic.cpp						//
// Date:	01.09.2012							//
// Author:	Max Pejs							//
//////////////////////////////////////////////////

#include "Statistic.h"

// load values from EEPROM
UInt16 Statistic::corrFramesCNT		= EEPROMMEM.readUInt16(CORRECT_FRM_CNT_MEM_ADDR);
UInt16 Statistic::invalidFramesCNT	= EEPROMMEM.readUInt16(INVALID_FRM_CNT_MEM_ADDR);
bool Statistic::IsActivated			= EEPROMMEM.readUInt8(STATISTICS_STATE_MEM_ADDR);

unsigned long Statistic::lastTimerStoreStat = 0;
extern unsigned long millis();

void Statistic::ResetStatistics(void)
{
	TRACE_NL("[INFO] Reset statistic");

	// reset counters
	corrFramesCNT = 0;
	invalidFramesCNT = 0;

	// resent content in EEPROM
	EEPROMMEM.write((UInt16) CORRECT_FRM_CNT_MEM_ADDR, (UInt16) 0);
	EEPROMMEM.write((UInt16) INVALID_FRM_CNT_MEM_ADDR, (UInt16) 0);
}

void Statistic::StoreStatistic()
{
	if(!IsActivated)
	{
		return;
	}

	unsigned long currentTime = millis();
	if( (currentTime - lastTimerStoreStat) > STATISTIC_UPDATE_TIME)
	{
		EEPROMMEM.write((UInt16) CORRECT_FRM_CNT_MEM_ADDR, corrFramesCNT);
		EEPROMMEM.write((UInt16) INVALID_FRM_CNT_MEM_ADDR, invalidFramesCNT);
		lastTimerStoreStat = currentTime;
	}
}

void Statistic::SendStatistic()
{
	if(!IsActivated)
	{
		sendStatisticAreDeactivated();
		return;
	}

	TRACE("[INFO] Correct: ");	TRACE(corrFramesCNT);
	TRACE(" Invalid: ");	TRACE(invalidFramesCNT);
	TRACE(" Quality: ");

	UInt8 nmb = 0;
	UInt16 frameSum = corrFramesCNT + invalidFramesCNT;

	// avoid null division
	if(frameSum != 0)
	{
		nmb = (UInt8)(( (UInt32)corrFramesCNT * 100) / (corrFramesCNT + invalidFramesCNT));
	}
	TRACE(nmb);	TRACE("%\n");
}

void Statistic::FrameReceived(bool valid)
{
	if(!IsActivated)
	{
		return;
	}

	if(valid)
	{
		corrFramesCNT++;
	}
	else
	{
		invalidFramesCNT++;
	}

	StoreStatistic();
}

void Statistic::sendStatisticAreDeactivated(void)
{
	TRACE_NL("Statistics are deactivated. For activating type \"staton\"");
}

void Statistic::SendStatus()
{
	TRACE("[INFO] Statistic are ");
	if(IsActivated)
	{
		TRACE("on");
	}
	else
	{
		TRACE("off");
	}
	TRACE("\n");
}

void Statistic::SetState(bool state)
{
	IsActivated = state;
	EEPROMMEM.write((UInt16) STATISTICS_STATE_MEM_ADDR, (UInt8)IsActivated);
	STATISTIC.SendStatus();
}